package cn.com.header.core.support.security.spring;


import cn.com.header.core.support.web.JsonViewData;
import cn.com.header.core.support.web.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * 登录失败返回JSON串
 * @author Liangzhongqiu
 * @date 2017/8/31 031
 * @time 20:57
 */
public class AjaxLoginFailureHandler implements AuthenticationFailureHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String message = "用户名或密码错误！";
        if(exception instanceof UsernameNotFoundException){
            logger.warn("用户名不存在！");
        }else if(exception instanceof BadCredentialsException){
            logger.warn("用户密码错误！");
        }else if(exception instanceof DisabledException){
            message = "对不起，该用户已被禁用！";
            logger.warn(message);
        }
        new JsonViewData(ResultCode.FAIL,message).write(response);
    }
}
